package com.maslyk.invitation;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.maslyk.invitation.entitybean.Salesman;
import com.maslyk.invitation.service.PersistenceService;
import com.maslyk.invitation.to.CurrentUserTO;

/**
 * 
 * @author Krzysztof.Maslyk
 *
 */
public class CustomRequestFilter implements Filter
{
	private PersistenceService service;
	
    public void init(FilterConfig config) throws ServletException
    {
    	ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    	service = (PersistenceService) springContext.getBean("persistenceService");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
//    	System.out.println("Kodowanie: "+request.getCharacterEncoding()+"Contenttype: "+request.getContentType());
    	
    	request.setCharacterEncoding("UTF-8");
    	response.setContentType("charset=UTF-8");
    	response.setCharacterEncoding("UTF-8");

    	HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        
        req.setCharacterEncoding("UTF-8");
        
        String param = req.getParameter("shippingAddress"); // cudowny kod ktory naprawia problem z kodowaniem - nie usuwac
        
        if(session.getAttribute("currentUserTO") == null && request.getParameter("login") == null)
        	request.getRequestDispatcher("/login_page.jsp").forward(request, response);
        else if(session.getAttribute("currentUserTO") == null && request.getParameter("login") != null)
        {
    	    String login = request.getParameter("login");
    	    String password = request.getParameter("password");

    	    Salesman salesman = login(login, password);
    	    
    	    //zalogowany
    	    if(salesman != null)
    	    {
    	    	CurrentUserTO currentUser = new CurrentUserTO(salesman);
    	    	session.setAttribute("currentUserTO", currentUser);
    	    	chain.doFilter(request, response);
    	    }
    	    else
    	    {
    	        request.getRequestDispatcher("/login_page_error.jsp").forward(request, response);
    	    }
        }
        else
        	chain.doFilter(request, response);
        
    }

    public void destroy()
    {
    }
    
    private Salesman login(String login, String password)
    {
    	return service.login(login, password);
    }
}
